package com.ruoyi.system.listener;

import com.aliyuncs.exceptions.ClientException;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.aliyun.SendMessage;
import com.ruoyi.system.Constants.CommonConstants;
import com.ruoyi.system.domain.ApproveCarbonCopy;
import com.ruoyi.system.domain.MsgConfiguration;
import com.ruoyi.system.domain.MsgLog;
import com.ruoyi.system.domain.ProcessTemplates;
import com.ruoyi.system.service.*;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 *   执行监听器
 *   start：在流程实例启动时触发。
 *   end：在流程实例结束时触发。
 *   take:流程连线被执行时触发。
 *   监听任务完成监听器   end触发
 *
 */
@Component
public class ProcessListener implements ExecutionListener {
    @Resource
    private RepositoryService repositoryService;
    @Resource
    private IProcessTemplatesService processTemplatesService;
    @Resource
    private IMsgConfigurationService msgConfigurationService;
    @Resource
    private IMsgLogService msgLogService;
    @Resource
    private IApproveCarbonCopyService approveCarbonCopyService;
    @Resource
    private ISysUserService userService;
    @Resource
    private ApproveMenuService approveMenuService;

    @Override
    public void notify(DelegateExecution execution) {
        //修改流程状态为已结束
        execution.setVariable(CommonConstants.PROCESS_STATUS,CommonConstants.BUSINESS_STATUS_4);
        //发送消息
        String templateId = (String)execution.getVariableInstance("templateId").getValue();
        ProcessTemplates processTemplates = processTemplatesService.selectProcessTemplatesByTemplateId(templateId);
        //审核通过消息
        Long startMsg = processTemplates.getEndMsg();
        MsgConfiguration msgConfiguration = msgConfigurationService.selectMsgConfigurationById(startMsg);
        String sendType = msgConfiguration.getSendType();

        //给发起人和抄送人发送消息
        //获取流程实例id
        String processInstanceId = execution.getProcessInstanceId();
        ApproveCarbonCopy approveCarbonCopy = new ApproveCarbonCopy();
        approveCarbonCopy.setProcessInstanceId(processInstanceId);
        //根据流程实例查询抄送人
        List<ApproveCarbonCopy> approveCarbonCopies = approveCarbonCopyService.selectApproveCarbonCopyList(approveCarbonCopy);
        List<Long> userIdList = approveCarbonCopies.stream().map(o -> o.getUserId()).collect(Collectors.toList());

        //todo 查询流程发起人添加到发送人列表


        for(Long userId : userIdList){
            MsgLog msgLog = new MsgLog();
            msgLog.setMsgContent(msgConfiguration.getMsgContent());
            msgLog.setMsgTitile(msgConfiguration.getMsgTitile());
            msgLog.setReceiver(String.valueOf(userId));
            SysUser user = userService.selectUserById(userId);
            String phonenumber = user.getPhonenumber();
            if("0".equals(sendType)){
                //站内消息
                msgLog.setSendType("0");
                msgLogService.insertMsgLog(msgLog);
            }else if("1".equals(sendType)){
                //短信
                sendTextMsg(String.valueOf(userId),phonenumber,msgConfiguration);
            }else if("2".equals(sendType)){
                //短信
                sendTextMsg(String.valueOf(userId),phonenumber,msgConfiguration);
                //站内消息
                msgLog.setSendType("0");
                msgLogService.insertMsgLog(msgLog);
            }
        }

        //判断流程类型做响应的业务逻辑
        String approveMenu = (String)execution.getVariable("approveMenu");
        String approveId = (String)execution.getVariable("approveId");
        if(StringUtils.isNotBlank(approveMenu)&&StringUtils.isNotBlank(approveId)){
            //审批完成
            approveMenuService.updateApproveMenuDataStatus(approveMenu,approveId,"1");
        }
    }

    //发送短信提醒
    public void sendTextMsg(String userId, String phonenumber,MsgConfiguration msgConfiguration){
        Integer msgCon = 1111;
        try {
            MsgLog msgLog = new MsgLog();
            msgLog.setMsgContent(msgConfiguration.getMsgContent());
            msgLog.setMsgTitile(msgConfiguration.getMsgTitile());
            msgLog.setReceiver(userId);
            //站内消息
            msgLog.setSendType("1");
            //消息发送失败
            if (!SendMessage.sendSms(phonenumber, msgCon)) {
                msgLog.setStatus("1");
                msgLogService.insertMsgLog(msgLog);
            }
            msgLogService.insertMsgLog(msgLog);
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

}
